<template>
  <div class="page-main">
    <query-page
      ref="detailTable"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="tableTotal"
      :has-line="false"
      title="采购逆向产品处理"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #top-container>
        <p-tabs
          v-model:value="activeTab"
          :is-show-num="false"
          :tab-list="tabList"
        ></p-tabs>
      </template>
      <template #container-side>
        <span v-permission="['scs:product-reverse:save']">
          <batchImport
            title="采购逆向产品处理"
            btn-tititle="Excel导入"
            export-type="apiUrl"
            file-code="delivery_reverseProcurement"
            import-url="/api/procurement/delivery/product-reverse/import"
            @finish="getData"
          ></batchImport>
        </span>
      </template>
      <template #iqsProveFile="{ record }">
        <a-popover
          title="查看质量证明文件"
          trigger="click"
          content-style="max-height:300px;overflow: auto;"
        >
          <a-button type="text">查看质量证明文件</a-button>
          <template #content>
            <div v-if="record.iqsProveFileList.length === 0">-</div>
            <div
              v-for="(item, index) in record.iqsProveFileList"
              :key="index"
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <p>{{ item.name }}</p>
              <div>
                <span
                  style="margin: 0 10px; color: #165dff; cursor: pointer"
                  @click="handleDown(item)"
                  >下载</span
                >
              </div>
            </div>
          </template>
        </a-popover>
      </template>
      <template #operate="{ record, rowIndex }">
        <a-button type="text" @click="handleDetail(record, rowIndex)"
          >详情</a-button
        >
        <a-button
          v-permission="['scs:product-reverse:update']"
          type="text"
          @click="handleEdit(1, record, rowIndex)"
          >紧急程度维护</a-button
        >
        <a-button
          v-permission="['scs:product-reverse:update']"
          type="text"
          @click="handleEdit(2, record, rowIndex)"
          >排故信息编辑</a-button
        >
        <a-button
          v-permission="['scs:product-reverse:update']"
          type="text"
          @click="handleEdit(3, record, rowIndex)"
          >故障品情况跟踪</a-button
        >
        <a-button
          v-permission="['scs:product-reverse:update']"
          type="text"
          @click="handleMoreEdit(record, rowIndex)"
          >故障品信息批量修改</a-button
        >
      </template>
    </query-page>
    <MaintenanceModal
      v-if="maintenanceModalVisible"
      v-model="maintenanceModalVisible"
      :page-model="pageModel"
      :select-id="selectRowId"
      @fetch-data="getData"
    />
    <EditModal
      v-if="editModalVisible"
      v-model="editModalVisible"
      :select-id="selectRowId"
    />
    <DetailModal
      v-if="detailModalVisible"
      v-model="detailModalVisible"
      :select-id="selectRowId"
    />
  </div>
</template>

<script lang="ts" setup>
  import {
    ref,
    watch,
    defineAsyncComponent,
    computed,
    reactive,
    provide,
    nextTick,
  } from 'vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import { getScsProductPage } from '@/api/reverse-procurement/product-handling';
  import batchImport from '@/common/components/batch-import/index.vue';
  import { info } from '@/common/utils/modal-promise';
  import { materialType } from '@/config/const';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../module-common/table-comp/base-table-config';
  import {
    formComponentConfig,
    formRenderConfig,
  } from '../module-common/form-comp/base-form-config';
  import MaintenanceModal from './maintenance-modal.vue';
  import { baseRenderKeys } from './baseData';
  import PTabs from './p-tabs.vue';

  const EditModal = defineAsyncComponent(() => import('./edit-modal.vue'));
  const DetailModal = defineAsyncComponent(() => import('./detail-modal.vue'));
  const tabList = ref(materialType);

  const detailTable = ref(null);
  const selectedKeys = ref([]);
  const activeTab = ref('2');
  const tableTotal = ref(0);
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);

  interface Tst {
    [index: string]: any;
  }
  const dataRenderBase = ref<Tst>({
    '2': baseRenderKeys.finishedProduct.formRenderKeys,
    '1': baseRenderKeys.standardPart.formRenderKeys,
    '3': baseRenderKeys.rawMaterial.formRenderKeys,

    '4': baseRenderKeys.zeroCom.formRenderKeys,

    '5': baseRenderKeys.forgingAndCasting.formRenderKeys,
  });
  const tableRenderBase = ref<Tst>({
    '2': baseRenderKeys.finishedProduct.newTableRenderKeys,
    '1': baseRenderKeys.standardPart.newTableRenderKeys,
    '3': baseRenderKeys.rawMaterial.newTableRenderKeys,

    '4': baseRenderKeys.zeroCom.newTableRenderKeys,

    '5': baseRenderKeys.forgingAndCasting.newTableRenderKeys,
  });
  // const selectionChange = (val: string[]) => {
  //   console.log('selectedKeys', val);
  // };
  const getData = async (queryInfo: object) => {
    const page = detailTable.value.getStatus();
    isLoading.value = true;
    const { data } = await getScsProductPage({
      ...queryInfo,
      ...page,
      mdsItemType: activeTab.value,
    });
    renderData.value = data.list.map((item) => {
      let iqsProveFileList = [];
      try {
        iqsProveFileList = JSON.parse(item.iqsProveFile) || [];
      } catch (error) {
        console.log(error);
      }
      return {
        ...item,
        iqsProveFileList,
      };
    });
    tableTotal.value = data.total;
    isLoading.value = false;
  };
  let selectedRow = reactive({});
  provide(
    'selectedRow',
    computed(() => {
      return selectedRow;
    })
  );
  const handleDown = (item) => {
    window.open(item.url);
  };
  // 初期话
  const initData = () => {
    // 获取筛选form的renderKey(表单渲染项)
    formRenderKeys.value = dataRenderBase.value[activeTab.value];
    tableRenderKeys.value = tableRenderBase.value[activeTab.value];
  };
  watch(
    () => activeTab.value,
    () => {
      initData();
      selectedKeys.value = [];
      nextTick(() => {
        getData();
      });
    }
  );

  const init = () => {
    initData();
  };
  const maintenanceModalVisible = ref(false);
  const detailModalVisible = ref(false);
  // 表格逻辑
  let selectRowList: Array<any> = [];
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const selectRowId = ref(null);
  const selectionChange = (rowKeys) => {
    if (rowKeys && rowKeys.length) {
      selectRowList = rowKeys;
      const [selectId] = selectRowList;
      selectRowId.value = selectId;
    }
  };
  // 按钮逻辑
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const pageModel = ref<number>(1);
  const handleEdit = async (val, row) => {
    selectRowId.value = row.id;
    pageModel.value = val;
    let selectRow =
      renderData.value.filter((item) => item.id === selectRowId.value) || null;
    selectRow = selectRow ? selectRow[0] : null;
    if (pageModel.value === 3) {
      if (selectRow && ![1, 2].includes(Number(selectRow.businessStatus))) {
        await info({
          title: '到货确认',
          content: `逆向产品处理单编号【${selectRow.id}】的制单状态不是【排故中】或【已到货】，不能编辑故障品情况跟踪！`,
          okText: '确认',
        });
        return;
      }
    }
    maintenanceModalVisible.value = true;
  };
  // 批量编辑
  const editModalVisible = ref(false);
  const handleDetail = (row) => {
    selectRowId.value = row.id;
    detailModalVisible.value = true;
    selectedRow = row;
  };
  const handleMoreEdit = (row) => {
    selectRowId.value = row.id;
    editModalVisible.value = true;
    selectedRow = row;
  };
  init();
</script>

<style lang="less" scoped>
  @import url('../module-common/common.less');
</style>
